import requests
import json
import cv2
import base64

import numpy as np


def cv2_to_base64(image):
    d = cv2.imencode('.jpg', image)[1]
    return base64.b64encode(d.tostring()).decode('utf8')


def base64_to_cv2(b64str):
    d1 = base64.b64decode(b64str.encode('utf8'))
    d2 = np.fromstring(d1, np.uint8)
    d3 = cv2.imdecode(d2, cv2.IMREAD_COLOR)
    return d3


if __name__ == '__main__':
    # 发送HTTP请求
    data = {'images': [cv2_to_base64(cv2.imread("./img/girl.jpg"))]}
    print(data)
    headers = {"Content-type": "application/json"}
    url = "http://49.235.95.23:8866/predict/deeplabv3p_xception65_humanseg"
    r = requests.post(url=url, headers=headers, data=json.dumps(data))

    # 打印预测结果
    print(base64_to_cv2(r.json()["results"][0]['data']))
    # print(base64_to_cv2(r.json()["results"]))
